package com.iamteer.day18.longtext;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.junit.Test;

public class AppBlob {
	private Connection con;
	private PreparedStatement pstmt;
	private ResultSet rs;
	
	private String url = "jdbc:mysql:///day18";
	private String user = "root";
	private String password = "123456";
	
	//1 保存二进制数据（写）
	@Test
	public void testSaveImage() {
		String sql = "INSERT INTO test(img) VALUES(?)";
		InputStream in = null;
		try {
			//连接数据库
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(url, user, password);
			
			//获取 PreparedStatement 对象
			pstmt = con.prepareStatement(sql);
			
			//设置参数
			in = AppBlob.class.getResourceAsStream("7.jpg");
			pstmt.setBinaryStream(1, in);
			
			//执行
			pstmt.executeUpdate();
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				in.close();
				pstmt.close();
				con.close();
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}
	
	//1 保存大文本（写）
	@Test
	public void testReadImage() {
		String sql = "SELECT img FROM test WHERE id=2";
		InputStream in = null;
		FileOutputStream out = null;
		try {
			//连接数据库
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(url, user, password);
			
			//获取 PreparedStatement 对象
			pstmt = con.prepareStatement(sql);
			
			//执行
			rs = pstmt.executeQuery();
			if (rs.next()) {
				in = rs.getBinaryStream("img");
				out = new FileOutputStream(new File("img.jpg"));
				int len = -1;
				byte b[] = new byte[1024];
				while ((len = in.read(b)) != -1) {
					out.write(b, 0, len);
				}
			}
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				out.close();
				in.close();
				pstmt.close();
				con.close();
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}
}
